package com.gonsin.ta.logic.parse.serialize;

import com.gonsin.ta.logic.enums.ConditionTypeEnum;
import com.gonsin.ta.logic.exceptions.TaException;
import com.gonsin.ta.logic.node.Node;
import com.gonsin.ta.logic.node.SignalNodeAdapter;
import com.gonsin.ta.logic.parse.condition.Executable;
import com.gonsin.ta.logic.parse.condition.WaitCondition;
import com.gonsin.ta.logic.process.SignalCenter;
import com.gonsin.ta.logic.process.TaBus;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
public class WaitConditionSerial extends ConditionSerial{

    @ApiModelProperty("等待的信号值")
    private String signalNode;

    /**
     * 超时时间
     */
    @ApiModelProperty("超时时间")
    private Long timeout;

    /**
     * 超时时间
     */
    @ApiModelProperty("超时时间的模板")
    private String timeoutModel;

    /**
     * 下一步操作
     */
    @ApiModelProperty("下一步操作")
    private List<TaDeserializable> next;


    /**
     * 超时时执行
     */
    @ApiModelProperty("超时时执行")
    private List<TaDeserializable> timeoutTask;

    private ConditionTypeEnum conditionType = ConditionTypeEnum.WAIT;

    @Override
    public Executable toExecutable(DeserializeContext deserializeContext) {

        Node node = TaBus.getNode(signalNode);
        if(node == null){
            throw new TaException("反序列化失败，找不到选择信号节点【{}】", signalNode);
        }
        if(!(node instanceof SignalNodeAdapter)){
            throw new TaException("反序列化失败，【{}】不是信号节点", signalNode);
        }

        SignalCenter signalCenter = deserializeContext.getSignalCenter();

        WaitCondition condition = new WaitCondition((SignalNodeAdapter) node, signalCenter);
        condition.setConditionId(this.getConditionId());
        List<Executable> nextExe = new ArrayList<>();
        for(TaDeserializable exe : next){
            nextExe.add(exe.toExecutable(deserializeContext));
        }
        condition.setNext(nextExe);
        condition.setTimeoutModel(timeoutModel);
        condition.setTimeout(timeout);


        List<Executable> timeoutExe = new ArrayList<>();
        for(TaDeserializable exe : timeoutTask){
            timeoutExe.add(exe.toExecutable(deserializeContext));
        }
        condition.setTimeoutTask(timeoutExe);
        return condition;
    }
}
